<template>
	<div class="container">
		<div class="el-card is-always-shadow diygw-col-24">
			<div class="el-card__body">
				<div class="mb8">
					<el-form class="flex flex-direction-row flex-wrap" :model="queryParams" :rules="queryParamsRules" ref="queryForm" label-width="80px">
						<div class="flex diygw-col-0">
							<el-form-item class="diygw-el-rate" prop="title_like" label="标题">
								<el-input type="text" placeholder="请输入标题查询" v-model="queryParams.title_like"> </el-input>
							</el-form-item>
						</div>
						<div class="flex diygw-col-0">
							<el-button type="primary" @click="handleQuery"> <SvgIcon name="ele-Search" /> 搜索 </el-button> <el-button @click="resetQuery"> <SvgIcon name="ele-Refresh" /> 重置 </el-button>
						</div>
					</el-form>
				</div>
				<div class="mb8">
					<el-button type="primary" plain @click="onOpenAddModule"> <SvgIcon name="ele-Plus" />新增 </el-button> <el-button type="danger" plain :disabled="multiple" @click="onTabelRowDel"> <SvgIcon name="ele-Delete" />删除 </el-button>
				</div>
				<el-table @selection-change="handleSelectionChange" v-loading="loading" :data="tableData" stripe border current-row-key="id" empty-text="没有数据" style="width: 100%">
					<el-table-column type="selection" width="55" align="center"></el-table-column>
					<el-table-column label="置顶" prop="title" align="center">
						<template #default="scope"> <el-tag style="cursor: pointer" v-if="scope.row.sortnum > 0" type="error" @click="updatenumApi(scope.row)"> 取消置顶 </el-tag><el-tag style="cursor: pointer" @click="ordernumApi(scope.row)" v-else> 置顶 </el-tag> </template>
					</el-table-column>
					<el-table-column label="商品图片" prop="img" align="center">
						<template #default="scope"> <diy-img style="width: 80px; height: 80px" :src="scope.row.img" fit="contain"></diy-img> </template>
					</el-table-column>
					<el-table-column label="商品名称" prop="title" align="center"> </el-table-column>
					<el-table-column label="商品价格" prop="price" align="center"> </el-table-column>
					<el-table-column label="总销量" prop="sellamonut" align="center"> </el-table-column>
					<el-table-column label="库存量" prop="amount" align="center"> </el-table-column>
					<el-table-column label="备注" prop="remark" align="center"> </el-table-column>
					<el-table-column label="数据状态" prop="status" align="center">
						<template #default="scope"> <el-tag v-if="scope.row.status == 1"> 上架 </el-tag><el-tag v-else> 下架 </el-tag> </template>
					</el-table-column>
					<el-table-column label="操作" align="center" fixed="right" width="180">
						<template #default="scope">
							<el-button type="primary" plain size="small" @click="onOpenEditModule(scope.row)"> <SvgIcon name="ele-Edit" />修改 </el-button> <el-button v-if="scope.row.id != 0" type="danger" plain size="small" @click="onTabelRowDel(scope.row)"> <SvgIcon name="ele-Delete" />删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页设置-->
				<div v-show="total > 0"><el-divider></el-divider> <el-pagination background :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" /></div>
			</div>
			<!-- 添加或修改参数配置对话框 -->
			<el-dialog :fullscreen="isFullscreen" width="1000px" v-model="isShowDialog" destroy-on-close title="商品" draggable center>
				<template #header="{ close, titleId, titleClass }">
					<h4 :id="titleId" :class="titleClass">商品</h4>
					<el-tooltip v-if="!isFullscreen" content="最大化" placement="bottom">
						<el-button class="diygw-max-icon el-dialog__headerbtn">
							<el-icon @click="isFullscreen = !isFullscreen">
								<FullScreen />
							</el-icon>
						</el-button>
					</el-tooltip>
					<el-tooltip v-if="isFullscreen" content="返回" placement="bottom">
						<el-button class="diygw-max-icon el-dialog__headerbtn">
							<el-icon @click="isFullscreen = !isFullscreen">
								<Remove />
							</el-icon>
						</el-button>
					</el-tooltip>
				</template>
				<el-form class="flex flex-direction-row flex-wrap" :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
					<div class="flex diygw-col-24">
						<el-tabs v-model="tabsTab" tab-position="top" @tab-click="handleClick">
							<el-tab-pane label="基本信息" name="1">
								<div class="flex flex-direction-row flex-wrap">
									<div class="flex diygw-col-24">
										<el-form-item
											:rules="[
												{
													required: true,
													trigger: 'blur',
													message: '商品名称不能为空'
												}
											]"
											class="diygw-el-rate"
											prop="title"
											label="商品名称"
										>
											<el-input type="text" placeholder="请输入商品名称" v-model="editForm.title"> </el-input>
										</el-form-item>
									</div>
									<div class="flex diygw-col-24">
										<el-form-item prop="cateId" class="diygw-el-rate" label="商品分类">
											<el-select clear-icon="CircleClose" suffix-icon="ArrowUp" placeholder="请选择" v-model="editForm.cateId" style="width: 100% !important">
												<el-option v-for="item in cates.rows" :key="item.id" :label="item.title" :value="item.id" />
											</el-select>
										</el-form-item>
									</div>
									<div class="flex diygw-col-24">
										<el-form-item
											:rules="[
												{
													required: true,
													trigger: 'blur',
													message: '商品主图不能为空'
												}
											]"
											prop="img"
											class="diygw-el-rate"
											label="商品主图"
										>
											<diy-uploadinput v-model="editForm.img" title="商品主图"></diy-uploadinput>
										</el-form-item>
									</div>
									<div class="flex diygw-col-24">
										<el-form-item prop="imgs" class="diygw-el-rate" label="商品轮播图">
											<diy-photo v-model="editForm.imgs"></diy-photo>
										</el-form-item>
									</div>
									<div class="flex diygw-col-24">
										<el-form-item prop="status" class="diygw-el-rate" label="商品状态">
											<el-radio-group v-model="editForm.status">
												<el-radio v-for="item in editFormData.statusDatas" :key="item.value" :label="item.value">
													{{ item.label }}
												</el-radio>
											</el-radio-group>
										</el-form-item>
									</div>
									<div class="flex diygw-col-24">
										<el-form-item prop="remark" class="diygw-el-rate" label="商品描述">
											<el-input type="textarea" rows="3" placeholder="请输入描述" v-model="editForm.remark"> </el-input>
										</el-form-item>
									</div>
								</div>
							</el-tab-pane>
							<el-tab-pane label="规格库存" name="2">
								<div class="flex flex-direction-row flex-wrap">
									<div class="flex diygw-col-24">
										<el-form-item prop="skuType" class="diygw-el-rate" label="规格类型">
											<el-radio-group v-model="editForm.skuType">
												<el-radio v-for="item in editFormData.skuTypeDatas" :key="item.value" :label="item.value">
													{{ item.label }}
												</el-radio>
											</el-radio-group>
										</el-form-item>
									</div>
									<div v-if="editForm.skuType == 1" class="flex flex-wrap diygw-col-24 flex-direction-column">
										<div class="flex diygw-col-24">
											<el-form-item
												:rules="[
													{
														type: 'number',
														required: true,
														trigger: 'blur',
														message: '请输入数字'
													}
												]"
												prop="price"
												class="diygw-el-rate"
												label="商品价格"
											>
												<el-input-number min="0" max="100" step="1" controls controls-position="right" placeholder="输入商品价格" v-model="editForm.price"> </el-input-number>
												<div class="diygw-help-text">商品的实际购买金额，最低0.01</div>
											</el-form-item>
										</div>
										<div class="flex diygw-col-24">
											<el-form-item
												:rules="[
													{
														type: 'number',
														required: true,
														trigger: 'blur',
														message: '请输入数字'
													}
												]"
												prop="linePrice"
												class="diygw-el-rate"
												label="切线价格"
											>
												<el-input-number min="0" max="100" step="1" controls controls-position="right" placeholder="输入切线价格" v-model="editForm.linePrice"> </el-input-number>
												<div class="diygw-help-text">划线价仅用于商品页展示</div>
											</el-form-item>
										</div>
										<div class="flex diygw-col-24">
											<el-form-item
												:rules="[
													{
														type: 'number',
														required: true,
														trigger: 'blur',
														message: '请输入数字'
													}
												]"
												prop="amount"
												class="diygw-el-rate"
												label="库存数量"
											>
												<el-input-number min="0" max="100" step="1" controls controls-position="right" placeholder="输入库存数量" v-model="editForm.amount"> </el-input-number>
												<div class="diygw-help-text">商品的实际库存数量，为0时用户无法下单</div>
											</el-form-item>
										</div>
									</div>
									<div v-else class="flex diygw-col-24">
										<el-form-item prop="skus" label="多规格">
											<diy-sku :columns="editFormData.skusColumns" v-model:skus="editForm.skus.skus" v-model:specs="editForm.skus.specs"></diy-sku>
										</el-form-item>
									</div>
								</div>
							</el-tab-pane>
							<el-tab-pane label="商品详情" name="3">
								<div class="flex flex-direction-row flex-wrap">
									<div class="flex diygw-col-24">
										<el-form-item
											:rules="[
												{
													required: true,
													trigger: 'blur',
													message: '商品详情不能为空哟'
												}
											]"
											prop="content"
											class="diygw-el-rate"
											label="商品详情"
										>
											<diy-editor v-model="editForm.content"></diy-editor>
										</el-form-item>
									</div>
								</div>
							</el-tab-pane>
						</el-tabs>
					</div>
				</el-form>
				<template #footer>
					<div class="dialog-footer flex justify-center"><el-button @click="closeDialog"> 取 消 </el-button> <el-button type="primary" @click="onSubmit" :loading="saveloading"> 保 存 </el-button></div>
				</template>
			</el-dialog>
		</div>
		<div class="clearfix"></div>
	</div>
</template>

<script>
	import { useRouter, useRoute } from 'vue-router';
	import { storeToRefs } from 'pinia';
	import { useUserInfo } from '@/stores/userInfo';

	import { ElMessageBox, ElMessage } from 'element-plus';
	import { deepClone, changeRowToForm } from '@/utils/other';
	import { addData, updateData, delData, listData } from '@/api';

	import DiyUploadinput from '@/components/upload/uploadinput.vue';
	import DiyPhoto from '@/components/upload/photo.vue';
	import DiySku from '@/components/sku/index.vue';
	import DiyEditor from '@/components/editor/index.vue';

	export default {
		components: {
			DiyUploadinput,
			DiyPhoto,
			DiySku,
			DiyEditor
		},
		data() {
			return {
				globalOption: {},
				userInfo: {},
				ordernum: {
					code: 200,
					msg: '设置成功'
				},
				updatenum: {
					code: 200,
					msg: '修改成功',
					data: {
						id: '1',
						sortnum: '0'
					}
				},
				cates: {
					rows: [
						{
							id: 0,
							title: '',
							remark: null,
							img: '',
							sortnum: null,
							status: '',
							userId: 0,
							createTime: '',
							updateTime: '',
							deleteTime: null
						}
					],
					total: 0,
					code: 0,
					msg: ''
				},
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 弹出层标题
				title: '',
				// 总条数
				total: 0,
				tableData: [],
				// 是否显示弹出层
				isFullscreen: false,
				isShowDialog: false,
				saveloading: false,
				tabsTab: '1',
				editFormInit: {},
				queryParamsInit: {},

				editFormData: {
					statusDatas: [
						{ value: '1', label: '上架' },
						{ value: '2', label: '下架' }
					],
					skuTypeDatas: [
						{ value: '1', label: '单规格' },
						{ value: '2', label: '多规格' }
					],
					skusColumns: [
						{ title: '图片地址', id: 'thumb', type: 'img' },
						{ title: '价格', id: 'price', type: 'number' },
						{ title: '划线价格', id: 'linePrice', type: 'number' },
						{ title: '库存', id: 'amount', type: 'number' },
						{ title: '备注', id: 'sku', type: 'text' }
					]
				},

				queryParams: {
					pageNum: 1,
					pageSize: 10,
					title_like: ''
				},

				queryParamsRules: {},

				editForm: {
					id: undefined,
					title: '',
					cateId: '',
					img: '',
					imgs: [],
					status: '1',
					remark: '',
					skuType: '1',
					price: '',
					linePrice: '',
					amount: '',
					skus: {
						skus: [],
						specs: []
					},
					content: ''
				},

				editFormRules: {}
			};
		},
		methods: {
			getParamData(e, row) {
				row = row || {};
				let dataset = e.currentTarget ? e.currentTarget.dataset : e;
				if (row) {
					dataset = Object.assign(dataset, row);
				}
				return dataset;
			},
			navigateTo(e, row) {
				let dataset = this.getParamData(e, row);
				let { type } = dataset;
				if (type == 'page' || type == 'inner' || type == 'href') {
					this.router.push({
						path: dataset.url,
						query: dataset
					});
				} else if (typeof this[type] == 'function') {
					this[type](dataset);
				} else {
					ElMessage.error('待实现点击事件');
				}
			},
			async init() {
				await this.catesApi();
			},
			// 置顶 API请求方法
			async ordernumApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/shop/goods/sortnum';
				let http_data = {};
				let http_header = {};

				http_data.id = param.id;
				let flag = await this.confirmFunction({ title: '确定置顶吗' });
				if (!flag) {
					ElMessage.error('你已取消');
					return;
				}
				let ordernum = await this.$http.post(http_url, http_data, http_header, 'json');
				this.ordernum = ordernum;
				this.resetQuery();
			},
			// 设置为0 API请求方法
			async updatenumApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/shop/goods/update';
				let http_data = {};
				let http_header = {};

				http_data.id = param.id;
				http_data.sortnum = 0;
				let flag = await this.confirmFunction({ title: '确定取消置顶吗' });
				if (!flag) {
					ElMessage.error('你已取消');
					return;
				}
				let updatenum = await this.$http.post(http_url, http_data, http_header, 'json');
				this.updatenum = updatenum;
				this.resetQuery();
			},
			// 分类 API请求方法
			async catesApi(param) {
				param = param || {};
				param = this.getParamData(param);
				let http_url = '/shop/cate/all';
				let http_data = {};
				let http_header = {};

				let cates = await this.$http.post(http_url, http_data, http_header, 'json');
				this.cates = cates;
			},

			// confirm 自定义方法
			async confirmFunction(param) {
				param = param || {};
				let thiz = this;
				let title = param && (param.title || param.title == 0) ? param.title : thiz.title || '';
				return new Promise((resolve) => {
					ElMessageBox({
						message: title,
						title: '警告',
						showCancelButton: true,
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							resolve(true);
						})
						.catch(() => {
							resolve(false);
						});
				});
			},
			// 打开弹窗
			openDialog(row) {
				if (row.id && row.id != undefined && row.id != 0) {
					this.editForm = changeRowToForm(row, this.editForm);
				} else {
					this.initForm();
				}
				this.isShowDialog = true;
				this.saveloading = false;
			},

			// 关闭弹窗
			closeDialog(row) {
				this.mittBus.emit('onEditAdmintableModule', row);
				this.isShowDialog = false;
			},

			// 保存
			onSubmit() {
				const formWrap = this.$refs.editFormRef;
				if (!formWrap) return;
				formWrap.validate((valid, fields) => {
					if (valid) {
						this.saveloading = true;
						if (this.editForm.skuType == 2 && this.editForm.skus && this.editForm.skus.skus.length == 0) {
							ElMessage.error('请设置多规格');
							return;
						}
						if (this.editForm.id != undefined && this.editForm.id != 0) {
							updateData('/shop/goods', this.editForm)
								.then(() => {
									ElMessage.success('修改成功');
									this.saveloading = false;
									this.closeDialog(this.editForm); // 关闭弹窗
								})
								.finally(() => {
									this.saveloading = false;
								});
						} else {
							addData('/shop/goods', this.editForm)
								.then(() => {
									ElMessage.success('新增成功');
									this.saveloading = false;
									this.closeDialog(this.editForm); // 关闭弹窗
								})
								.finally(() => {
									this.saveloading = false;
								});
						}
					} else {
						let message = '';
						if (fields && Object.keys(fields).length > 0) {
							let field = fields[Object.keys(fields)[0]];
							let messages = field.map((item) => {
								return item.message;
							});
							message = messages.join(',');
						}
						ElMessage.error('验证未通过！' + message);
					}
				});
			},
			// 表单初始化，方法：`resetFields()` 无法使用
			initForm() {
				this.editForm = deepClone(this.editFormInit);
			},
			/** 查询商品列表 */
			handleQuery() {
				this.loading = true;
				listData('/shop/goods', this.queryParams).then((response) => {
					this.tableData = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.queryParams = deepClone(this.queryParamsInit);
				this.handleQuery();
			},

			// 打开新增商品弹窗
			onOpenAddModule(row) {
				row = [];
				this.title = '添加商品';
				this.openDialog(row);
			},
			// 打开编辑商品弹窗
			onOpenEditModule(row) {
				this.title = '修改商品';
				this.initForm();
				this.openDialog(row);
			},
			/** 删除按钮操作 */
			onTabelRowDel(row) {
				let thiz = this;
				const id = row.id || this.ids;
				ElMessageBox({
					message: '是否确认删除选中的商品?',
					title: '警告',
					showCancelButton: true,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					return delData('/shop/goods', id).then(() => {
						thiz.handleQuery();
						ElMessage.success('删除成功');
					});
				});
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map((item) => item.id);
				this.single = selection.length != 1;
				this.multiple = !selection.length;
			},

			//分页页面大小发生变化
			handleSizeChange(val) {
				this.queryParams.pageSize = val;
				this.handleQuery();
			},
			//当前页码发生变化
			handleCurrentChange(val) {
				this.queryParams.pageNum = val;
				this.handleQuery();
			}
		},
		async mounted() {
			this.router = useRouter();
			this.globalOption = useRoute().query;
			const stores = useUserInfo();
			const { userInfos } = storeToRefs(stores);
			this.userInfo = userInfos;
			await this.init();
			this.editFormInit = deepClone(this.editForm);
			this.queryParamsInit = deepClone(this.queryParams);
			this.handleQuery();
			this.mittBus.on('onEditAdmintableModule', () => {
				this.handleQuery();
			});
		},
		beforeUnmount() {
			this.mittBus.off('onEditAdmintableModule');
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		font-size: 12px;
	}
</style>
